﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using ST.WX.Common;
using ST.WX.Common.Enums;
using ST.WX.MP.TplMsg;
using System;
using System.Collections.Generic;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("wx/tplmsgconfig")]
	public class WX_TplMsgConfigController : MyBaseController
	{
		private readonly IServiceWXTplMsgConfig service;
		private readonly IServiceWXAppConfig serviceWXAppConfig;
		private readonly WXTplMsgApi wxTplMsgApi;
		public WX_TplMsgConfigController(IServiceWXTplMsgConfig _service,
			IServiceWXAppConfig _serviceWXAppConfig,
			WXTplMsgApi _wxTplMsgApi,
			ILogger<WX_TplMsgConfigController> _logger) : base(_logger)
		{
			service = _service;
			serviceWXAppConfig = _serviceWXAppConfig;
			wxTplMsgApi = _wxTplMsgApi;
		}

		private VMS_WX_TplMsgConfig GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_WX_TplMsgConfig();
			vm.pnum = TextHelper.GetInt(paras, "pnum");
			vm.psize = TextHelper.GetInt(paras, "psize");
			vm.sortorder = TextHelper.GetString(paras, "sortorder");

			vm.title = TextHelper.GetString(paras, "title");
			vm.appid = TextHelper.GetString(paras, "appid");
			vm.code = TextHelper.GetString(paras, "code");
			vm.orgids = TextHelper.GetInts(paras, "orgid");
			vm.type = TextHelper.GetIntNullable(paras, "type");
			vm.ids = TextHelper.GetInts(paras, "ids");
			return vm;
		}

		private VMS_WX_TplMsgConfig GetSearchModelFromGetRequest()
		{
			var vm = new VMS_WX_TplMsgConfig();
			vm.pnum = TextHelper.GetInt(Request.Query["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Query["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Query["sortorder"]);

			vm.title = TextHelper.GetString(Request.Query["title"]);
			vm.appid = TextHelper.GetString(Request.Query["appid"]);
			vm.code = TextHelper.GetString(Request.Query["code"]);
			vm.orgids = TextHelper.GetInts(Request.Query["orgid"]);
			vm.type = TextHelper.GetIntNullable(Request.Query["type"]);
			vm.ids = TextHelper.GetInts(Request.Query["ids"]);
			return vm;
		}

		private VMS_WX_TplMsgConfig GetSearchModelFromPostRequest()
		{
			var vm = new VMS_WX_TplMsgConfig();
			vm.pnum = TextHelper.GetInt(Request.Form["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Form["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Form["sortorder"]);

			vm.title = TextHelper.GetString(Request.Form["title"]);
			vm.appid = TextHelper.GetString(Request.Form["appid"]);
			vm.code = TextHelper.GetString(Request.Form["code"]);
			vm.orgids = TextHelper.GetInts(Request.Form["orgid[]"]);
			vm.type = TextHelper.GetIntNullable(Request.Form["type"]);
			vm.ids = TextHelper.GetInts(Request.Form["ids[]"]);
			return vm;
		}

		[HttpPost("search")]
		public IActionResult Search([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				searchModel.orgids = new int[] { sessionCurrent.OrgID };
				PageData pageData = service.GetPageList(searchModel, sessionCurrent);

				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List(string code, string title)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				ViewBag.CurrentMenu = "DA8EE90DAC";//子菜单，需要修改
				ViewBag.PrintTpl = code;
				ViewBag.Title = string.IsNullOrEmpty(title) ? "微信模板消息管理" : title;
				ViewBag.TplMsgTypes = GetEnums(typeof(TplMsgType));
				ViewBag.States = GetStateOptions();
				ViewBag.AppTypes = GetAppTypeOptions();
				ViewBag.Apps = serviceWXAppConfig.GetAllList(sessionCurrent);
				return View();
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "打开页面失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("save")]
		public ActionResult Save([FromBody] WX_TplMsgConfig model)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				//if (!string.IsNullOrEmpty(model.Footer))//去除换行等字符
				//{
				//	model.Footer = model.Footer.Replace("\r", "").Replace("\n", "");
				//}
				int rowID = service.AddOrUpdate(model, sessionCurrent);

				JsonResultBase ret = new JsonResultBase(rowID);
				return ret;
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "保存失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("detail")]
		public IActionResult ViewJson([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				int id = TextHelper.GetInt(paras, "id");

				var model = service.GetViewDetail(id, sessionCurrent);

				if (model == null)
				{
					return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
				}

				return new JsonResultBase(model);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("delete")]
		public JsonResult Delete([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = service.Delete(rowID, sessionCurrent);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("sync")]
		public JsonResult Sync([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var appID = TextHelper.GetString(paras, "appid");
				if (string.IsNullOrEmpty(appID))
				{
					throw new ArgumentException("要同步的应用ID不能为空");
				}
				var appConfig = serviceWXAppConfig.LoadOrGet(appID);
				var tplList = wxTplMsgApi.GetAll(appConfig.AppID, appConfig.AppSecret);
				var result = service.Sync(appID, tplList, sessionCurrent);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (ArgumentException ex)
			{
				return new JsonResultBase(false, ex.Message, 400);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message, 400);
			}
			catch (WXException ex)
			{
				return new JsonResultBase(false, ex.Message, 400);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, 500);
			}
		}

		[ValidateSession]
		[HttpGet("poplist")]
		public IActionResult PopList(string code, string callback)
		{
			ViewData["code"] = code;
			ViewData["callback"] = callback;
			return View();
		}

		protected List<SelectListItem> GetAppTypeOptions()
		{
			List<SelectListItem> lst = new List<SelectListItem>();
			lst.Add(new SelectListItem() { Value = ((int)WXAppType.XCX).ToString(), Text = "小程序" });
			lst.Add(new SelectListItem() { Value = ((int)WXAppType.MP).ToString(), Text = "公众号" });
			return lst;
		}

		protected List<SelectListItem> GetStateOptions()
		{
			List<SelectListItem> lst = new List<SelectListItem>();
			lst.Add(new SelectListItem() { Value = ((int)WXTplState.已停用).ToString(), Text = "已停用" });
			lst.Add(new SelectListItem() { Value = ((int)WXTplState.已删除).ToString(), Text = "已删除" });
			lst.Add(new SelectListItem() { Value = ((int)WXTplState.正常).ToString(), Text = "正常" });
			return lst;
		}
	}
}